package com.fwj.user.service.user.rbac;

import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.constant.DataConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.PageRequest;
import com.fwj.core.common.model.PageResponse;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.core.common.model.ResponseEnum;
import com.fwj.user.api.rbac.RBACAuthService;
import com.fwj.user.dao.rbac.RBACAuthMapper;
import com.fwj.user.entity.rbac.auth.Auth;
import com.fwj.user.model.rbac.auth.AuthVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author: fwj
 * @Data: 2022/5/1 17:43
 * @Version 1.0
 * @Description:
 */

@Service
public class RBACAuthServiceImpl implements RBACAuthService {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(RBACAuthServiceImpl.class);

    @Autowired
    private RBACAuthMapper authMapper;

    @Override
    @Transactional
    public ResponseDTO saveAuth(Auth auth) {
        try {
            Auth execAuth = buildAuth(auth);
            authMapper.insertSelective(execAuth);
            return new ResponseDTO().success();
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    private Auth buildAuth(Auth auth) {
        Auth retAuth = new Auth();
        //生成权限编码
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String number = simpleDateFormat.format(timestamp) + CommonUtils.generateUniqueNumber();

        retAuth.setAuthNumber(number);
        retAuth.setAuthName(auth.getAuthName());
        retAuth.setCreator(auth.getCreator());
        retAuth.setCreateTime(timestamp);
        retAuth.setUpdateTime(timestamp);
        retAuth.setStatus(DataConstant.NORMAL);
        return retAuth;
    }

    @Override
    @Transactional
    public ResponseDTO deleteAuth(String authNumber) {
        try {
            Example example = new Example(Auth.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("authNumber",authNumber);
            authMapper.deleteByExample(example);
            return new ResponseDTO().success();
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    @Override
    public ResponseDTO queryAuth(JSONObject jsonObject) {
        try {
            PageRequest pageRequest = JSONObject.parseObject(jsonObject.toJSONString(),PageRequest.class);
            PageHelper.startPage(pageRequest.getPage(), pageRequest.getPageSize());
            Example example = buildAuthExample(pageRequest.getRequestBody());
            PageInfo<Auth> pageInfo = new PageInfo<>(authMapper.selectByExample(example));
            PageResponse<AuthVo> pageResponse = new PageResponse<>();
            pageResponse.setPageTotal(pageInfo.getTotal());
            List<AuthVo> authVoList = JSONObject.parseArray(JSONObject.toJSONString(pageInfo.getList()),AuthVo.class);
            pageResponse.setResponseBody(authVoList);
            return new ResponseDTO().success().setData(pageResponse);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    private Example buildAuthExample(JSONObject requestBody) {
        Example example = new Example(Auth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",DataConstant.NORMAL);
        if (CommonUtils.isEmpty(requestBody)){ return example; }
        AuthVo authVo = JSONObject.parseObject(requestBody.toJSONString(),AuthVo.class);
        if (CommonUtils.isNotEmpty(authVo.getAuthNumber())){
            criteria.andLike("roleNumber",authVo.getAuthNumber());
        }
        if (CommonUtils.isNotEmpty(authVo.getAuthName())){
            criteria.andLike("roleName",authVo.getAuthName());
        }
        return example;
    }

    @Override
    public JSONObject getAuthDetails(String authNumber) {
        try {
            Example example = new Example(Auth.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("roleNumber",authNumber);
            Auth auth = authMapper.selectOneByExample(example);
            AuthVo authVo = JSONObject.parseObject(JSONObject.toJSONString(auth),AuthVo.class);
            return new ResponseDTO().success().setData(authVo);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO<>().fail();
        }
    }

    @Override
    public Auth findAuthByAuthNumber(String authNumber) {
        try {
            Example example = new Example(Auth.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("authNumber", authNumber);
            criteria.andEqualTo("status", DataConstant.NORMAL);
            return authMapper.selectOneByExample(example);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

}
